import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import {  Modal,Icon,Tabs,message,Table,Dropdown,Menu,Button,Input,Form ,Row,Col,Select,Switch,Popconfirm,Pagination,DatePicker,Spin} from 'antd';
const Search = Input.Search;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import SearchPanel from '../common/SearchPanel';
import RemarkModal from '../common/RemarkModal';
import DataAnalyzeTable from '../common/DataAnalyzeTable';

import {
  ANALYZE_TABLE_TYPE,
  ASSET_LEVEL
} from '../constants/index';
import api from '../api';
import moment from 'moment';
import {bind_change, bind_toggle} from '../common/State';
const {RangePicker} = DatePicker


export default class CircleBuyingList extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           // page:0,
           // total:1,
           // pageSize:10,
           loading:false,
           period:3,
           data:{
            cycleBuying:{},
            currentRecycle:{},
            currentBuying:{},
           },
           recyclerPagination:{
            page:1,
            pageSize:10,
            total:1,
           },
           buyingPagination:{
            page:1,
            pageSize:10,
            total:1,
           },
           session:{},
         }
    }

    async componentWillMount(){
      // let router = await this.props.route;
      // let {page,pageSize} = this.state
      // this.setState({
      //   session,
      // })
      let{period} = this.state;
      this.doFetch(period);
    }
    async componentWillReceiveProps(nextProps){

    }
    //查询列表
    async doFetch(period){

      this.setState({
        loading:true
      })
      let {data,recyclerPagination,buyingPagination} = this.state;
      let result = await api('/property/getCycleBuying/getAll',{period});

      if (result.cycleBuying.success) {
        data.cycleBuying = result.cycleBuying.data;
      }else{
        message.error(result.cycleBuying.message || "获取数据失败");
      }
      if (result.currentRecycle.success) {
        data.currentRecycle = result.currentRecycle.data;
        recyclerPagination.page = result.currentRecycle.data.pageNumber;
        recyclerPagination.pageSize = result.currentRecycle.data.pageSie;
        recyclerPagination.total = result.currentRecycle.totalItem;
      }else{
        message.error(result.currentRecycle.message || "获取数据失败");
      }
      if (result.currentBuying.success) {
        data.currentBuying = result.currentBuying.data;
        buyingPagination.page = result.currentBuying.data.pageNumber;
        buyingPagination.pageSize = result.currentBuying.data.pageSie;
        buyingPagination.total = result.currentBuying.totalItem;
      }else{
        message.error(result.currentBuying.message || "获取数据失败");
      }
      this.setState({
        data,
        loading:false,
        period,
      })

    }

    formatNumber(num) {
      return (num / 10000).toFixed(2).toString();
    }

    toMoneyFormat(number){
       let s = this.formatNumber(number);
        if(/[^0-9\.]/.test(s)) return "invalid value";
        s=s.replace(/^(\d*)$/,"$1.");
        s=(s+"00").replace(/(\d*\.\d\d)\d*/,"$1");
        s=s.replace(".",",");
        var re=/(\d)(\d{3},)/;
        while(re.test(s))
            s=s.replace(re,"$1,$2");
        s=s.replace(/,(\d\d)$/,".$1");
        return s.replace(/^\./,"0.")
    }

    

    exportTable(e){
      if (e.key == "ALL") {
        
      }else if (e.key == "SELECTED") {
        
      }else{

      }
    }

    onChangePeriod(value){
      this.setState({
        loading:true,
      })
      this.doFetch(value);
    }
    






    
    //分页
    async currentRecycleChangePage(pagination,filters,sorter){
      let{period,recyclerPagination,data} = this.state;

      let result = await api('/property/getCurrentRecycle/list',{period:period,pageNumber:pagination.current,pageSize:pagination.pageSize});
      if (result.success) {
        data.currentRecycle = result.data;
        recyclerPagination.page = pagination.current;
        recyclerPagination.pageSize = pagination.pageSize;
        this.setState({
          data,
          recyclerPagination,
        })
      }else{
        message.error(result.message);
      }
    }

    async buyingChangePage(pagination,filters,sorter){
      let{period,buyingPagination,data} = this.state;

      let result = await api('/property/getCurrentBuying/list',{period:period,pageNumber:pagination.current,pageSize:pagination.pageSize});
      if (result.success) {
        data.currentBuying = result.data;
        buyingPagination.page = pagination.current;
        buyingPagination.pageSize = pagination.pageSize;
        this.setState({
          data,
          buyingPagination,
        })
      }else{
        message.error(result.message);
      }
    }

    // changePageSizer(current,size){
    //   current = current - 1;
    //   this.doFetch(current,size);
    // }

    
    // quickJumper(pageNumber,pageSize){
    //   pageNumber = pageNumber - 1;
    //   this.doFetch(pageNumber,pageSize);
    // }

    
    render() {

        var {list=[],recyclerPagination,buyingPagination}=this.state;
        let {
          cycleBuying,
          currentRecycle,
          currentBuying,
        }=this.state.data

        return (
          <Spin spinning={this.state.loading}>
          <div className="bgWhite marginL25 marginB40">
            <div style={{"padding":"20px","background":"#F7F7F7"}}>
              <div className="containerWithBorder paddingT15 bgWhite">
                <div className="marginL15 marginR15">
                  <div style={{"float":"left",marginTop:"10px"}}>循环购买</div>
                  <div className="text-right">
                    <Select 
                        onChange={this.onChangePeriod.bind(this)}
                        style={{width:230}}
                        defaultValue="3"
                      >
                        <Option key="3" value="3">第3期（2018-09-01 至 2018-11-30）</Option>
                        <Option key="2" value="2">第2期（2018-06-01 至 2018-08-31）</Option>
                        <Option key="1" value="1">第1期（2018-03-01 至 2018-05-31）</Option>
                      </Select>
                    <Button
                      className='marginL10'
                    >导出<Icon type="download" /></Button>
                  </div>
                </div>

                <Row className="marginT20">
                  <Col 
                    span={4} 
                    className="containerWithRightBorder containerWithTopBorder padding15" 
                    
                  >
                    <div className="marginL15">
                      <p>回收款金额</p>
                      <p style={{fontSize:26}}>{
                        cycleBuying.cycle_amount?
                          this.toMoneyFormat(cycleBuying.cycle_amount)
                        :
                          "0.00"
                        }<span style={{fontSize:14}}>万元</span></p>
                      <p>笔数{
                        cycleBuying.cycle_count?
                          cycleBuying.cycle_count
                        :
                          0
                      }笔</p>
                    </div>
                  </Col>
                  <Col 
                    span={4} 
                    className="containerWithRightBorder containerWithTopBorder padding15" 
                    style={{paddingRight:"15px"}}
                  >
                    <div className="marginL15">
                      <p>计提利息费用</p>
                      <p style={{fontSize:26}}>{
                        cycleBuying.accrual_fee?
                          this.toMoneyFormat(cycleBuying.accrual_fee)
                        :
                          "0.00"
                        }<span style={{fontSize:14}}>万元</span></p>
                      <p>上期{
                        cycleBuying.accrual_fee_beginning?
                          this.toMoneyFormat(cycleBuying.accrual_fee_beginning)
                        :
                          "0.00"
                        }万元</p>
                    </div>
                  </Col>
                  <Col 
                    span={4} 
                    className="containerWithRightBorder containerWithTopBorder padding15" 
                    style={{paddingRight:"15px"}}
                  >
                    <div className="marginL15">
                      <p>可循环购买金额</p>
                      <p style={{fontSize:26}}>{
                        cycleBuying.can_cycle_buy_amount?
                          this.toMoneyFormat(cycleBuying.can_cycle_buy_amount)
                        :
                          "0.00"
                        }<span style={{fontSize:14}}>万元</span></p>
                      <p>期初{
                        cycleBuying.can_cycle_buy_amount_beginning?
                          this.toMoneyFormat(cycleBuying.can_cycle_buy_amount_beginning)
                        :
                          "0.00"
                        }万元</p>
                    </div>
                  </Col>
                  <Col 
                    span={4} 
                    className="containerWithRightBorder containerWithTopBorder padding15" 
                    style={{paddingRight:"15px"}}
                  >
                    <div className="marginL15">
                      <p>循环购买金额</p>
                      <p style={{fontSize:26}}>{
                        cycleBuying.cycle_buy_amount?
                          this.toMoneyFormat(cycleBuying.cycle_buy_amount)
                        :
                          "0.00"
                        }<span style={{fontSize:14}}>万元</span></p>
                      <p>单笔{
                        cycleBuying.cycle_buy_count?
                          cycleBuying.cycle_buy_count
                        :
                          "0"
                      }笔</p>
                    </div>
                  </Col>
                  <Col 
                    span={4} 
                    className="containerWithRightBorder containerWithTopBorder padding15" 
                    style={{paddingRight:"15px"}}
                  >
                    <div className="marginL15">
                      <p>回收款金额使用率</p>
                      <p style={{fontSize:26}}>{
                        cycleBuying.cycle_amount_use_rate?
                          cycleBuying.cycle_amount_use_rate
                        :
                          "0"
                      }%</p>
                      <p>上期{
                        cycleBuying.cycle_amount_use_rate_beginning?
                          cycleBuying.cycle_amount_use_rate_beginning
                        :
                          "0"
                      }%</p>
                    </div>
                  </Col>
                  <Col 
                    span={4} 
                    className="containerWithTopBorder padding15" 
                    style={{paddingRight:"15px"}}
                  >
                    <div className="marginL15">
                      <p>闲置资金金额</p>
                      <p style={{fontSize:26}}>{
                        cycleBuying.unused_amount?

                          this.toMoneyFormat(cycleBuying.unused_amount)
                        :
                          "0.00"
                      }<span style={{fontSize:14}}>万元</span></p>
                      <p>闲置比例{
                        cycleBuying.unused_amount_rate?
                          cycleBuying.unused_amount_rate
                        :
                          "0"
                      }%</p>
                    </div>
                  </Col>
                </Row>
              </div>

              <Table
                columns={this.getBuyBackColumns()}
                dataSource={
                  currentRecycle && currentRecycle.pageResult ?
                    currentRecycle.pageResult
                  :
                    []
                }
                title={() => {
                        return (<div className="marginL15">当期回收</div>)
                    }
                }
                className="containerWithBorder marginT20 bgWhite"
                pagination={recyclerPagination}
                style={{"width":"100%"}}
                onChange={this.currentRecycleChangePage.bind(this)}
                rowKey={(record,index) => index}
              >
              </Table>

              <Table
                columns={this.getBuyColumns()}
                dataSource={
                  currentBuying && currentBuying.pageResult ?
                   currentBuying.pageResult
                  :
                   []
                }
                title={() => {
                        return (<div className="marginL15">当期购买</div>)
                    }
                }
                className="containerWithBorder marginT20 bgWhite"
                pagination={buyingPagination}
                onChange={this.buyingChangePage.bind(this)}
                rowKey={(record,index) => index}
              >
              </Table>

            </div>
          </div>
          </Spin>
               
        );
    }

    getBuyBackColumns(){
      let {session} = this.state;
      let columns = [
            {
              title: '编号',
              dataIndex: 'number',
              key: 'number',
            }, {
              title: '债务人',
              dataIndex: 'buyer',
              key: 'buyer',
            }, {
              title: '应收账款日',
              dataIndex: 'predict_date',
              key: 'predict_date',
            },{
              title: '分级',
              dataIndex: 'level',
              key: 'level',
              render:(level) =>{
                return ASSET_LEVEL[level];
              },
            }, {
              title: '回收款金额',
              dataIndex: 'money_sum',
              key: 'money_sum',
            },{
              title: '回收日期',
              dataIndex: 'recycle_date',
              key: 'recycle_date',
            }

        ];

        return columns
    }

    getBuyColumns(){
      let {session} = this.state;
      let columns = [
            {
              title: '编号',
              dataIndex: 'number',
              key: 'number',
            }, {
              title: '债务人',
              dataIndex: 'buyer',
              key: 'buyer',
            }, {
              title: '应收账款日',
              dataIndex: 'predict_date',
              key: 'predict_date',
            },{
              title: '分级',
              dataIndex: 'level',
              key: 'level',
              render:(level) =>{
                return ASSET_LEVEL[level];
              },
            }, {
              title: '回收款金额',
              dataIndex: 'money_sum',
              key: 'money_sum',
            },{
              title: '回收日期',
              dataIndex: 'recycle_date',
              key: 'recycle_date',
            }
        ];

        return columns
    }

    
}

CircleBuyingList.contextTypes= { router: React.PropTypes.object.isRequired};
